package com.shj.web.exception;

import com.shj.model.ErrorInfo;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description TODO 统一异常处理
 * @Author songhuajian
 * @Date 2020/3/4 21:02
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @description 异常处理
     * @author songhuajian
     * @date 2020/3/26 16:07
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorInfo<Object> handleException(HttpServletRequest request, Exception exception){
        ErrorInfo<Object> errorInfo = new ErrorInfo<>();
        errorInfo.setCode(400);
        errorInfo.setMsg(exception.getMessage());
        errorInfo.setUrl(request.getRequestURI());
        errorInfo.setData(exception.getMessage());
        exception.printStackTrace();
        return errorInfo;
    }

    /**
     * @description 参数校验错误处理
     * @author songhuajian
     * @date 2020/3/19 14:01
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ErrorInfo<Object> handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException exception) {
        ErrorInfo<Object> errorInfo = new ErrorInfo<>();
        errorInfo.setCode(400);
        errorInfo.setMsg("参数校验异常");
        errorInfo.setUrl(request.getRequestURI());
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = exception.getBindingResult().getAllErrors().get(0);
        errorInfo.setData(objectError.getDefaultMessage());
        return errorInfo;
    }

}
